package com.cy.myblog.filter;

import com.cy.myblog.model.Tuser;
import com.cy.myblog.pageModel.User;
import com.cy.myblog.service.UserServiceI;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
	    HttpServletResponse res = (HttpServletResponse)response;
	    HttpSession session = req.getSession();

	    Object obj = session.getAttribute("loginUser");
	    	    
	    if(obj == null){
	    	Cookie[] cookies = req.getCookies();
	    	
	    	if(cookies != null && cookies.length > 1){
	    		String account = null;
	    		String pwd = null;

	    		for(Cookie c:cookies){
	    			if(!c.getName().equals("cookieuser")) continue;

					if(StringUtils.isNotBlank(c.getValue())){
						//需要注意这里cookie的内容不能使用一些符号,如:':',思考解决方法为使用encodeURI()和decodeURI()进行编码解码.此方法没有实验过.
						account = StringUtils.substringBetween(c.getValue(), "account_", "pwd");
						pwd = StringUtils.substringBetween(c.getValue(), "pwd_", ".");
					}
	    			
	    		}

	    		if(account !=null && pwd != null){
	    			User user = new User(account,pwd);
	    			String[] xmlcfg = new String[]{"classpath:spring-content.xml","spring-hibernate.xml"};
	    			ApplicationContext ac = new ClassPathXmlApplicationContext(xmlcfg);
	    			UserServiceI userService = (UserServiceI) ac.getBean("userService");
	    			Tuser tu = userService.getByHql(user);
	    			if(tu != null){
						tu.setLogintime(new Date());
						userService.update(tu);
	    				session.setAttribute("loginUser", tu);
	    			}
	    		}
	    		
	    	}
	    }
	    chain.doFilter(req, res);
	}

	@Override
	public void destroy() {
	}

}
